package com.heima.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.mapper.ApUserMapper;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Map;
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ResponseResult<Map<String, Object>> login(LoginDto dto) {
        if (ObjectUtil.hasEmpty(dto.getPhone(), dto.getPassword())) {
            return ResponseResult.okResult(MapUtil.<String, Object>builder()
                    .put("token", AppJwtUtil.getToken(0L))
                    .build());
        }
        ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
        if (ObjectUtil.isEmpty(apUser)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        }
        String salt = apUser.getSalt();
        String md5Password = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        if (ObjectUtil.notEqual(md5Password, apUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "用户名或密码错误");
        }
        apUser.setPassword(null);
        apUser.setSalt(null);
        return ResponseResult.okResult(MapUtil.<String, Object>builder()
                .put("token", AppJwtUtil.getToken(Convert.toLong(apUser.getId())))
                .put("user", apUser)
                .build());
    }
}
